package com.eshop.modules.mp.service.impl;

import org.slf4j.LoggerFactory;
import cn.hutool.json.JSONUtil;
import java.io.File;
import cn.hutool.http.HttpUtil;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import java.io.IOException;
import java.util.Iterator;
import com.eshop.utils.FileUtil;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.eshop.common.utils.QueryHelpPlus;
import com.eshop.modules.mp.service.dto.WechatLiveGoodsDto;
import java.util.LinkedHashMap;
import com.github.pagehelper.PageInfo;
import java.util.Map;
import org.springframework.data.domain.Pageable;
import com.eshop.modules.mp.service.dto.WechatLiveGoodsQueryCriteria;
import com.eshop.exception.BadRequestException;
import com.eshop.enums.LiveGoodsEnum;
import cn.hutool.core.util.ObjectUtil;
import cn.binarywang.wx.miniapp.bean.live.WxMaLiveGoodInfo;
import java.io.Serializable;
import cn.binarywang.wx.miniapp.bean.live.WxMaLiveResult;
import cn.binarywang.wx.miniapp.api.WxMaService;
import me.chanjar.weixin.common.error.WxErrorException;
import java.util.Collection;
import com.eshop.modules.mp.config.WxMaConfiguration;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;
import com.eshop.dozer.service.IGenerator;
import org.slf4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Service;
import com.eshop.modules.mp.service.WechatLiveGoodsService;
import com.eshop.modules.mp.domain.WechatLiveGoods;
import com.eshop.modules.mp.service.mapper.WechatLiveGoodsMapper;
import com.eshop.common.service.impl.BaseServiceImpl;

@Service
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = { Exception.class })
public class WechatLiveGoodsServiceImpl extends BaseServiceImpl<WechatLiveGoodsMapper, WechatLiveGoods> implements WechatLiveGoodsService
{
    private static final Logger log;
    private final IGenerator generator;
    @Value("${file.path}")
    private String uploadDirStr;
    
    public WechatLiveGoodsServiceImpl(final IGenerator generator) {
        this.generator = generator;
    }
    
    public boolean synchroWxOlLive(final List<Integer> goodsIds) {
        try {
            final WxMaService wxMaService = WxMaConfiguration.getWxMaService();
            final WxMaLiveResult liveInfos = wxMaService.getLiveGoodsService().getGoodsWareHouse((List)goodsIds);
            final List<WechatLiveGoods> convert = (List<WechatLiveGoods>)this.generator.convert(liveInfos.getGoods(), (Class)WechatLiveGoods.class);
            this.saveOrUpdateBatch((Collection)convert);
        }
        catch (WxErrorException e) {
            e.printStackTrace();
        }
        return true;
    }
    
    public void removeGoods(final Long id) {
        this.removeById((Serializable)id);
        try {
            final WxMaService wxMaService = WxMaConfiguration.getWxMaService();
            wxMaService.getLiveGoodsService().deleteGoods(Integer.valueOf(id.intValue()));
        }
        catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
    
    public void updateGoods(final WechatLiveGoods resources) {
        final WechatLiveGoods wechatLiveGoods = (WechatLiveGoods)this.getById((Serializable)resources.getGoodsId());
        try {
            final WxMaService wxMaService = WxMaConfiguration.getWxMaService();
            final WxMaLiveGoodInfo goods = (WxMaLiveGoodInfo)this.generator.convert(resources, (Class)WxMaLiveGoodInfo.class);
            if (ObjectUtil.isNotEmpty(wechatLiveGoods)) {
                if (!LiveGoodsEnum.IS_Audit_2.getValue().equals(wechatLiveGoods.getAuditStatus())) {
                    if (LiveGoodsEnum.IS_Audit_0.getValue().equals(wechatLiveGoods.getAuditStatus())) {
                        resources.setCoverImgUrl(this.uploadPhotoToWx(wxMaService, resources.getCoverImgeUrl()).getMediaId());
                    }
                    else {
                        if (LiveGoodsEnum.IS_Audit_1.getValue().equals(wechatLiveGoods.getAuditStatus())) {
                            throw new BadRequestException("商品审核中不允许修改");
                        }
                        if (LiveGoodsEnum.IS_Audit_3.getValue().equals(wechatLiveGoods.getAuditStatus())) {
                            resources.setCoverImgUrl(this.uploadPhotoToWx(wxMaService, resources.getCoverImgeUrl()).getMediaId());
                            wxMaService.getLiveGoodsService().updateGoods(goods);
                            wxMaService.getLiveGoodsService().auditGoods(goods.getGoodsId());
                            return;
                        }
                    }
                }
            }
            final boolean wxMaLiveResult = wxMaService.getLiveGoodsService().updateGoods(goods);
            this.saveOrUpdate(resources);
        }
        catch (WxErrorException e) {
            throw new BadRequestException(e.toString());
        }
    }
    
    public Map<String, Object> queryAll(final WechatLiveGoodsQueryCriteria criteria, final Pageable pageable) {
        this.getPage(pageable);
        final PageInfo<WechatLiveGoods> page = (PageInfo<WechatLiveGoods>)new PageInfo((List)this.queryAll(criteria));
        final Map<String, Object> map = new LinkedHashMap<String, Object>(2);
        final List<WechatLiveGoodsDto> goodsDtos = (List<WechatLiveGoodsDto>)this.generator.convert(page.getList(), (Class)WechatLiveGoodsDto.class);
        goodsDtos.forEach(i -> i.setId(i.getGoodsId()));
        map.put("content", goodsDtos);
        map.put("totalElements", page.getTotal());
        return map;
    }
    
    public List<WechatLiveGoods> queryAll(final WechatLiveGoodsQueryCriteria criteria) {
        return (List<WechatLiveGoods>)((WechatLiveGoodsMapper)this.baseMapper).selectList((Wrapper)QueryHelpPlus.getPredicate(WechatLiveGoods.class, criteria));
    }
    
    public void download(final List<WechatLiveGoodsDto> all, final HttpServletResponse response) throws IOException {
        final List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        for (final WechatLiveGoodsDto yxWechatLiveGoods : all) {
            final Map<String, Object> map = new LinkedHashMap<String, Object>();
            map.put("关联商品id", yxWechatLiveGoods.getProductId());
            map.put("商品图片", yxWechatLiveGoods.getCoverImgeUrl());
            map.put("商品小程序路径", yxWechatLiveGoods.getUrl());
            map.put("价格类型 1：一口价（只需要传入price，price2不传） 2：价格区间（price字段为左边界，price2字段为右边界，price和price2必传） 3：显示折扣价（price字段为原价，price2字段为现价， price和price2必传）", yxWechatLiveGoods.getPriceType());
            map.put(" price", yxWechatLiveGoods.getPrice());
            map.put(" price2", yxWechatLiveGoods.getPrice2());
            map.put("商品名称", yxWechatLiveGoods.getName());
            map.put("1, 2：表示是为api添加商品，否则是直播控制台添加的商品", yxWechatLiveGoods.getThirdPartyTag());
            map.put("审核单id", yxWechatLiveGoods.getAuditId());
            map.put("审核状态 0：未审核，1：审核中，2:审核通过，3审核失败", yxWechatLiveGoods.getAuditStatus());
            list.add(map);
        }
        FileUtil.downloadExcel((List)list, response);
    }
    
    public boolean saveGoods(final WechatLiveGoods resources) {
        final WxMaService wxMaService = WxMaConfiguration.getWxMaService();
        try {
            resources.setCoverImgUrl(this.uploadPhotoToWx(wxMaService, resources.getCoverImgeUrl()).getMediaId());
            final WxMaLiveGoodInfo goods = (WxMaLiveGoodInfo)this.generator.convert(resources, (Class)WxMaLiveGoodInfo.class);
            final WxMaLiveResult wxMaLiveResult = wxMaService.getLiveGoodsService().addGoods(goods);
            resources.setGoodsId((long)wxMaLiveResult.getGoodsId());
            resources.setAuditId((long)wxMaLiveResult.getAuditId());
            this.save(resources);
        }
        catch (WxErrorException e) {
            throw new BadRequestException(e.toString());
        }
        return true;
    }
    
    private WxMediaUploadResult uploadPhotoToWx(final WxMaService wxMaService, String picPath) throws WxErrorException {
        final String filename = (int)System.currentTimeMillis() + ".png";
        final String downloadPath = this.uploadDirStr + filename;
        final long size = HttpUtil.downloadFile(picPath, cn.hutool.core.io.FileUtil.file(downloadPath));
        picPath = downloadPath;
        final File picFile = new File(picPath);
        WechatLiveGoodsServiceImpl.log.info("picFile name : {}", picFile.getName());
        final WxMediaUploadResult wxMediaUploadResult = wxMaService.getMediaService().uploadMedia("image", picFile);
        WechatLiveGoodsServiceImpl.log.info("wxMpMaterialUploadResult : {}", JSONUtil.toJsonStr(wxMediaUploadResult));
        return wxMediaUploadResult;
    }
    
    static {
        log = LoggerFactory.getLogger((Class)WechatLiveGoodsServiceImpl.class);
    }
}
